package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.kaishengit.entity.User;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.RowMapper;

public class UserDao {

	private DBHelp<User> db = new DBHelp<User>();
	
	public void save(User user) {
		String sql = "insert into t_user(id,username,password,email,ip,lastaccesstime,pic,active,enable) values(?,?,?,?,?,?,?,?,?)";
		db.executeSQL(sql, user.getId(),user.getUsername(),user.getPassword(),user.getEmail(),user.getIp(),user.getLastaccesstime(),user.getPic(),user.getActive(),user.getEnable());
	}
	
	public void update(User user) {
		String sql = "update t_user set username=?,password=?,email=?,ip=?,lastaccesstime=?,pic=?,active=?,enable=? where id = ?";
		db.executeSQL(sql, user.getUsername(),user.getPassword(),user.getEmail(),user.getIp(),user.getLastaccesstime(),user.getPic(),user.getActive(),user.getEnable(),user.getId());
	}
	
	public User findById(String id) {
		String sql = "select id,username,password,email,ip,lastaccesstime,pic,active,enable,createtime from t_user where id = ?";
		return db.executeQueryToObject(sql, new UserRowMapper(), id);
	}
	
	public User findByName(String username) {
		String sql = "select id,username,password,email,ip,lastaccesstime,pic,active,enable,createtime from t_user where username = ?";
		return db.executeQueryToObject(sql, new UserRowMapper(), username);
	}
	
	private class UserRowMapper implements RowMapper<User> {

		public User mapRow(ResultSet rs) throws SQLException {
			User user = new User();
			user.setActive(rs.getBoolean("active"));
			user.setCreatetime(rs.getString("createtime"));
			user.setEmail(rs.getString("email"));
			user.setEnable(rs.getBoolean("enable"));
			user.setId(rs.getString("id"));
			user.setIp(rs.getString("ip"));
			user.setLastaccesstime(rs.getString("lastaccesstime"));
			user.setPassword(rs.getString("password"));
			user.setPic(rs.getString("pic"));
			user.setUsername(rs.getString("username"));
			return user;
		}
		
	}
}
